package com.xian.wsim.controller;

import com.xian.wsim.dto.MessageDto;
import com.xian.wsim.entity.MessageInfo;
import com.xian.wsim.service.MessageService;
import com.xian.wsim.util.ResponseUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class MessageController {

    @Autowired
    private MessageService messageService;

    @GetMapping("/messages/history")
    @CrossOrigin(origins = "*")
    public ResponseEntity<Map<String, List<MessageDto>>> getMessagesBetween(
            @RequestParam Long senderId, @RequestParam Long receiverId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        List<MessageInfo> messageInfos = messageService.getMessagesBetween(senderId, receiverId, timestampToLocalDateTime(Long.valueOf(startTime)), timestampToLocalDateTime(Long.valueOf(endTime)));
        List<MessageDto> messageDtos = new ArrayList<>();
        for (MessageInfo messageInfo : messageInfos) {
            MessageDto messageDto = new MessageDto();
            BeanUtils.copyProperties(messageInfo, messageDto);
            messageDtos.add(messageDto);
        }
        return ResponseUtil.success(messageDtos);
    }

    /**
     * 将时间戳（毫秒）转换为 LocalDateTime 对象
     * @param timestamp 时间戳，单位为毫秒
     * @return 转换后的 LocalDateTime 对象
     */
    public static LocalDateTime timestampToLocalDateTime(long timestamp) {
        return Instant.ofEpochMilli(timestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
    }
}